﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace NG
{
    class RolesHandler:IRolesHandler
    {
        private string tableName = "[dbo].[Roles]";
      
        public void addRole(Roles role)
        {
            DBConnect con = new DBConnect();
            string tbn = "[" + con.dbName + "]." + this.tableName;
            if (con.OpenConnection() == false)
            {
                throw new System.Exception("Couldn't connect to the Database");
            }

            string query = "INSERT INTO " + tbn + " (roleNO,roleName,roleDesc) VALUES (" + role.roleNum + ",'" + role.roleName + "','" + role.roleDesc + "');";

            try
            {
                SqlCommand cmd = new SqlCommand(query, con.connection);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            if (con.CloseConnection() == false)
            {
                throw new System.Exception("Couldn't disconnect from the Database");
            }

        }

        public void deleteRole(Roles role)
        {
            DBConnect con = new DBConnect();
            string tbn = "[" + con.dbName + "]." + this.tableName;

            if (con.OpenConnection() == false)
            {
                throw new System.Exception("Couldn't connect to the Database");
            }

            string query = "DELETE FROM " + tbn + " WHERE roleNo = " + role.roleNum;
            SqlCommand cmd = new SqlCommand(query, con.connection);
            cmd.ExecuteNonQuery();

            if (con.CloseConnection() == false)
            {
                throw new System.Exception("Couldn't disconnect from the Database");
            }
        }

        public void updateRole(Roles role, Roles newrole)
        {
            DBConnect con = new DBConnect();
            string tbn = "[" + con.dbName + "]." + this.tableName;
            if (con.OpenConnection() == false)
            {
                throw new System.Exception("Couldn't connect to the Database");
            }
            string query = "UPDATE" + tbn + " SET " +
               " roleName='" + newrole.roleName + "', roleDesc='" + newrole.roleDesc + "'"
                + "WHERE roleNo=" + role.roleNum;
            SqlCommand cmd = new SqlCommand(query, con.connection);
            cmd.ExecuteNonQuery();
            if (con.CloseConnection() == false)
            {
                throw new System.Exception("Couldn't disconnect from the Database");
            }
        }
    }
}
